package com.limh.readers.fragment

import android.content.Intent
import android.os.Handler
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import butterknife.BindView
import com.limh.readers.R
import com.limh.readers.activity.ArtListActivity
import com.limh.readers.bean.Magazine
import com.limh.readers.widget.recyclerview.adapter.CommonAdapter
import com.limh.readers.widget.recyclerview.adapter.MultiItemTypeAdapter
import com.limh.readers.widget.recyclerview.base.ViewHolder
import com.limh.readers.widget.recyclerview.decoration.SpacesItemDecoration
import com.limh.readers.comm.Comm
import com.limh.readers.net.BaseRetrofit
import com.limh.readers.net.ServerApi
import com.limh.readers.utils.GsonUtils
import com.limh.readers.utils.LogUtil
import com.limh.readers.utils.SharePreferUtils
import com.limh.readers.utils.Utils
import com.squareup.picasso.Picasso
import rx.schedulers.Schedulers

/**
 * Function:
 * author: limh
 * time:2017/7/26
 * 期刊列表
 */
class PeriodListFragment : BaseFragment() {

    @BindView(R.id.recycler_period)
    lateinit var recyclePeriod: RecyclerView

    lateinit var periods: MutableList<Magazine>
    lateinit var title: String
    lateinit var adapter: CommonAdapter<Magazine>
    val TAG = "PeriodListFragment"
    override fun findViews(inflater: LayoutInflater?, container: ViewGroup?): View {
        return inflater?.inflate(R.layout.fragment_period, container, false) as View
    }

    override fun initViews() {
        val mLayoutManager = GridLayoutManager(context, 2, GridLayoutManager.VERTICAL, false)
        recyclePeriod.layoutManager = mLayoutManager
        recyclePeriod.addItemDecoration(SpacesItemDecoration(Utils.dip2px(context, 10f),
                Utils.dip2px(context, 10f)))
    }

    override fun initDatas() {

        title = arguments.getString("title")
        LogUtil.d(TAG,"share="+SharePreferUtils.get(activity, title, ""))
        if ("" == SharePreferUtils.get(activity, title, ""))
            getPeriod(title)
        else {
            LogUtil.d(TAG, title + ":缓存中获取")
            periods = GsonUtils.str2List(SharePreferUtils.get(activity, title, "")
                    as String, Magazine::class.java)
            handler.sendEmptyMessage(0x123)
        }
    }

    fun getPeriod(name: String) {
        val params = mapOf(Pair("name", name),Pair("token", Comm.TOKEN))
        val service: ServerApi = BaseRetrofit().createService(ServerApi::class.java)
        service.getMagazine(params)
                .subscribeOn(Schedulers.newThread())
                .subscribeOn(Schedulers.io())
                .subscribe({ response ->
                    LogUtil.d(TAG, response.toString())
                    periods = GsonUtils.str2List(GsonUtils.Gson2Str(response.getData()), Magazine::class.java)
                    SharePreferUtils.put(activity, title, GsonUtils.Gson2Str(response.getData()))
                    handler.sendEmptyMessage(0x123)
                }, { t -> LogUtil.d(TAG, t.toString()) }, {})
    }

    private val handler = Handler(Handler.Callback { msg ->
        when (msg.what) {
            0x123 -> {
                for(item in periods){
                    LogUtil.d(TAG,item.toString())
                }
                adapter = object : CommonAdapter<Magazine>(context, R.layout.view_item_grid, periods) {
                    override fun convert(holder: ViewHolder, t: Magazine, position: Int) {
                        holder.setText(R.id.txt_item_period, t.period!!)
                        if (!TextUtils.isEmpty(t.coverLink))
                            Picasso.with(context).load(t.coverLink).into(holder.getView<View>
                            (R.id.image_item_cover) as ImageView)
                    }
                }
                adapter.setOnItemClickListener(object : MultiItemTypeAdapter.OnItemClickListener {
                    override fun onItemClick(view: View, holder: RecyclerView.ViewHolder, position: Int) {
                        LogUtil.d(TAG, "点击：" + periods.get(position).period)
                        val intent = Intent(activity, ArtListActivity::class.java)
                        intent.putExtra("name", periods[position].name)
                        intent.putExtra("period", periods[position].period)
                        intent.putExtra("link", periods[position].link)
                        startActivity(intent)
                    }
                })
                recyclePeriod.adapter = adapter
            }
        }
        true
    })

}